/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *   this.val = (val===undefined ? 0 : val)
 *   this.left = (left===undefined ? null : left)
 *   this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  if (!root) {
    return [];
  }
  const result = [];

  function dealNode({ val, left, right }, level) {
    if (!result[level]) {
      result[level] = [];
    }
    if (val !== null) {
      result[level].push(val)
    }
    if (left !== null) {
      dealNode(left, level + 1);
    }
    if (right !== null) {
      dealNode(right, level + 1);
    }
  }

  dealNode(root, 0);

  return result;
};

const root = { val: 3, left: { val: 9, left: null, right: null }, right: { val: 20, left: { val: 15, left: null, right: null }, right: { val: 7, left: null, right: null } } };
const result = levelOrder(root);
console.log(result);